package com.hech.hmall.service.impl;

import com.hech.hmall.dao.IUserDao;
import com.hech.hmall.entity.UserEntity;
import com.hech.hmall.exception.UserException;
import com.hech.hmall.service.IUserService;
import com.hech.hmall.util.Md5Util;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @author hanjiafeng
 * @date 2021/5/6 20:56
 * @desc todo
 */
@Service
public class UserServiceImpl implements IUserService {

    private final IUserDao userDao;

    public UserServiceImpl(IUserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public int register(UserEntity userEntity) {
        String newPassword = Md5Util.getMd5Encoding(userEntity.getPassword());
        userEntity.setPassword(newPassword);
        return userDao.insertSelective(userEntity);
    }

    @Override
    public Boolean checkElement(String eleKey, String eleValue) {
        UserEntity userEntity = new UserEntity();
        Field[] fields = userEntity.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.getName().equals(eleKey)) {
                try {
                    field.setAccessible(true);
                    field.set(userEntity, eleValue);
                    field.setAccessible(false);
                    break;
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return userDao.selectSelective(userEntity).size() > 0;
    }

    @Override
    public UserEntity login(String account, String password) throws UserException {
        UserEntity userEntity = new UserEntity();
        userEntity.setAccount(account);
        List<UserEntity> userEntityList = userDao.selectSelective(userEntity);
        if (userEntityList.size() == 0) {
            throw new UserException("用户名不存在");
        } else if (userEntityList.size() != 1) {
            throw new UserException("服务器内部错误，请联系管理员");
        }
        userEntity = userEntityList.get(0);
        if (!Md5Util.getMd5Encoding(password).equals(userEntity.getPassword())) {
            throw new UserException("密码错误");
        }
        return userEntity;
    }
}
